
/**
 * 处理file本地路径图片转为blob
 * @param {String} content 粘贴板内容
 * @param {event} e
 * @returns String
 */
export const convertFileToBlob = (content, e) => {
  if (!e) {
    return content
  }
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(content, 'text/html')
    const imgs = doc.querySelectorAll('img')
    const clipData = e.clipboardData || window.Clipboard
    let rtf = clipData.getData('text/rtf')
    const result = extractImageDataFromRtf(rtf)
    imgs.forEach((img, idx) => {
      const src = img.getAttribute('src')
      if (src && src.startsWith('file:')) {
        let boldFile = convertBase64ToBlob(result[idx].base64)
        img.setAttribute('src', URL.createObjectURL(boldFile))
      }
    })
    return doc.body.innerHTML
  } catch (e) {
    return content
  }
}

/**
  * 从html代码中匹配返回图片标签img的属性src的值的集合
  * @param htmlData
  * @return Array
  */
export const findAllImgSrcsFromHtml = (htmlData: string) => {
  const imgReg = /<img.*?(?:>|\/>)/gi
  const srcReg = /src=["']?([^"']*?)["']?(?:\s|>|\/>)/i

  const arr = htmlData.match(imgReg)
  if (!arr || !arr.length) {
    return false
  }

  const srcArr: string[] = []
  for (const img of arr) {
    const src = img.match(srcReg)
    if (src && src[1]) {
      srcArr.push(src[1])
    }
  }

  return srcArr
}

/**
 * 从rtf内容中匹配返回图片数据的集合
 * @param rtfData
 * @return Array
 */
export const extractImageDataFromRtf = (rtfData: string) => {
  if (!rtfData) {
    return []
  }

  const regexPictureHeader = /{\\pict[\s\S]+?({\\\*\\blipuid\s?[\da-fA-F]+)[\s}]*/
  const regexPicture = new RegExp(
    '(?:(' + regexPictureHeader.source + '))([\\da-fA-F\\s]+)\\}',
    'g'
  )
  const images = rtfData.match(regexPicture)
  const result = []

  if (images) {
    for (const image of images) {
      let imageType: string | null = null

      if (image.includes('\\pngblip')) {
        imageType = 'image/png'
      } else if (image.includes('\\jpegblip')) {
        imageType = 'image/jpeg'
      }

      if (imageType) {
        result.push({
          hex: image.replace(regexPictureHeader, '').replace(/[^\da-fA-F]/g, ''),
          type: imageType
        })
      }
    }
  }

  return result
}

/**
 * 将html内容中img标签的属性值替换
 * @param htmlData html内容
 * @param imageSrcs html中img的属性src的值的集合
 * @param imagesHexSources rtf中图片数据的集合，与html内容中的img标签对应
 * @param isBase64Data 是否是Base64的图片数据
 * @return String
 */
export const replaceImagesFileSourceWithInlineRepresentation = (
  htmlData: string,
  imageSrcs: string[],
  imagesHexSources: any[],
  isBase64Data = true
) => {
  if (imageSrcs.length === imagesHexSources.length) {
    for (let i = 0; i < imageSrcs.length; i++) {
      const newSrc = isBase64Data
        ? `data:${imagesHexSources[i].type
        };base64,${_convertHexToBase64(imagesHexSources[i].hex)}`
        : imagesHexSources[i]

      htmlData = htmlData.replace(imageSrcs[i], newSrc)
    }
  }

  return htmlData
}

/**
 * 十六进制转base64
 */
export const _convertHexToBase64 = (hexString: string) => {
  return btoa(
    hexString
      .match(/\w{2}/g)
      .map((char) => {
        return String.fromCharCode(parseInt(char, 16))
      })
      .join('')
  )
}

// 新增 base64 转 Blob 方法
export const base64ToBlob = (base64: string, type: string): Blob => {
  const byteCharacters = atob(base64)
  const byteArrays = []

  for (let offset = 0; offset < byteCharacters.length; offset += 512) {
    const slice = byteCharacters.slice(offset, offset + 512)
    const byteNumbers = new Array(slice.length)

    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    const byteArray = new Uint8Array(byteNumbers)
    byteArrays.push(byteArray)
  }

  return new Blob(byteArrays, { type })
}
